<template>
  <div class="container">
    <topTitle
      :titleText="filterField.date + titleText"
      :back="true"
      @gobackTriser="goBack"
    ></topTitle>
    <div class="mainCon">
      <el-form :model="formData" :rules="rules" ref="scoreForm">
        <el-form-item label="设置地区" class="row-padding-bottom">
          <el-select
            v-model="filterField.areaId"
            filterable
            placeholder="请选择"
            @change="changeArea"
          >
            <el-option
              v-for="(item, index) in areas"
              :key="index"
              :label="item.value"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-table
          :data="formData.tableList"
          v-loading="loading"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          border
          :span-method="objectSpanMethod"
        >
          <el-table-column
            prop="className"
            label="指标类别"
            align="center"
            :formatter="formatTd"
            min-width="15%"
          ></el-table-column>
          <el-table-column
            prop="itemName"
            label="指标名称"
            align="center"
            :formatter="formatTd"
            min-width="15%"
          ></el-table-column>
          <el-table-column
            prop="score"
            label="指标分值"
            align="center"
            :formatter="formatTd"
            min-width="8%"
          ></el-table-column>
          <el-table-column align="center" :formatter="formatTd" min-width="30%">
            <!-- eslint-disable-next-line -->
            <template slot="header" slot-scope="scope">
              <span style="color: red">*</span>扣分/得分/加分
            </template>
            <template slot-scope="scope">
              <el-form-item
                v-if="scope.row.itemCode === 'REPORT_DATA_QUALITY'"
                :prop="'tableList.' + scope.$index + '.detailScore'"
                :rules="rules.bonusScore"
                style="margin-top: 22px; padding: 0 30px"
                label-width="0"
              >
                <el-input v-model="scope.row.detailScore"></el-input>
              </el-form-item>
              <el-form-item
                v-else-if="scope.row.itemCode === 'PROJECT_RECORD'"
                :prop="'tableList.' + scope.$index + '.detailScore'"
                :rules="rules.reduceScore"
                style="margin-top: 22px; padding: 0 30px"
                label-width="0"
              >
                <el-input v-model="scope.row.detailScore"></el-input>
              </el-form-item>
              <el-form-item
                v-else
                :prop="'tableList.' + scope.$index + '.detailScore'"
                :rules="rules.detailScore"
                style="margin-top: 22px; padding: 0 30px"
                label-width="0"
              >
                <el-input v-model="scope.row.detailScore"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="说明"
            align="center"
            :formatter="formatTd"
            min-width="30%"
          >
            <template slot-scope="scope">
              <el-form-item
                style="margin-top: 22px; padding: 0 30px"
                label-width="0"
              >
                <el-input
                  :disabled="
                    validErrList.findIndex((v) => v === scope.$index) != -1
                  "
                  :maxlength="200"
                  v-model="scope.row.description"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关数据"></emptyTable>
          </div>
        </el-table>
      </el-form>
      <div style="text-align: center">
        <el-button
          class="commonBut saveBtn saveScore"
          v-if="!loading"
          @click.native="saveScore('scoreForm')"
          >保存</el-button
        >
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'FillScoreAllocation',
  data() {
    var validateScore = (rule, value, callback) => {
      let currentIndex = rule.field.split('.')[1] * 1
      let score = this.formData.tableList[currentIndex].score
      let reg = /^(([1-9]\d*)(\.\d{1,2})?|0\.([1-9]|\d[1-9])|0)$/
      if (!value && value !== 0) {
        if (this.validErrList.findIndex((v) => v === currentIndex) === -1) {
          this.validErrList.push(currentIndex)
        }
        callback(new Error('请输入分值'))
      } else if (value * 1 > score) {
        if (this.validErrList.findIndex((v) => v === currentIndex) === -1) {
          this.validErrList.push(currentIndex)
        }
        callback(new Error('应小于等于指标分值'))
      } else if (!reg.test(value)) {
        if (this.validErrList.findIndex((v) => v === currentIndex) === -1) {
          this.validErrList.push(currentIndex)
        }
        callback(new Error('分值需大于等于0，且支持小数点后2位'))
      } else {
        if (this.validErrList.findIndex((v) => v === currentIndex) != -1) {
          this.validErrList.remove(currentIndex)
        }
        callback()
      }
    }
    var validateBonusScore = (rule, value, callback) => {
      let currentIndex = rule.field.split('.')[1] * 1
      let reg = /^(([1-9]\d*)(\.\d{1,2})?|0\.([1-9]|\d[1-9])|0)$/
      if (!value && value !== 0) {
        if (this.validErrList.findIndex((v) => v === currentIndex) === -1) {
          this.validErrList.push(currentIndex)
        }
        callback(new Error('请输入分值'))
      } else if (!reg.test(value)) {
        if (this.validErrList.findIndex((v) => v === currentIndex) === -1) {
          this.validErrList.push(currentIndex)
        }
        callback(new Error('分值需大于等于0，且支持小数点后2位'))
      } else if (value * 1 > 10000) {
        callback(new Error('分值需小于等于10000'))
      } else {
        if (this.validErrList.findIndex((v) => v === currentIndex) != -1) {
          this.validErrList.remove(currentIndex)
        }
        callback()
      }
    }
    var validateReduceScore = (rule, value, callback) => {
      let currentIndex = rule.field.split('.')[1] * 1
      let reg = /^((\-[1-9]\d*)(\.\d{1,2})?|\-0\.([1-9]|\d[1-9])|0)$/
      if (!value && value !== 0) {
        if (this.validErrList.findIndex((v) => v === currentIndex) === -1) {
          this.validErrList.push(currentIndex)
        }
        callback(new Error('请输入分值'))
      } else if (!reg.test(value)) {
        if (this.validErrList.findIndex((v) => v === currentIndex) === -1) {
          this.validErrList.push(currentIndex)
        }
        callback(new Error('分值需小于等于0，且支持小数点后2位'))
      } else if (value * 1 < -10000) {
        callback(new Error('分值需大于等于-10000'))
      } else {
        if (this.validErrList.findIndex((v) => v === currentIndex) != -1) {
          this.validErrList.remove(currentIndex)
        }
        callback()
      }
    }
    return {
      titleText: '月度考核评分设置',
      validErrList: [],
      areas: [],
      formData: {
        tableList: [],
      },
      rules: {
        reduceScore: [{ validator: validateReduceScore, trigger: 'blur' }],
        bonusScore: [{ validator: validateBonusScore, trigger: 'blur' }],
        detailScore: [{ validator: validateScore, trigger: 'blur' }],
      },
      filterField: {
        date: '',
        areaId: '',
      },
      isShow: false,
      loading: true,
      isShowUpdate: true,
    }
  },
  async created() {
    await this.getAreaList()
    this.filterField.date = this.$route.query.date
    this.filterField.areaId = this.$route.query.areaId
    this.getFillScoreList(this.filterField)
  },
  methods: {
    changeArea() {
      this.getFillScoreList(this.filterField)
    },
    // 获取地区
    getAreaList() {
      return this.axios({
        method: 'get',
        url: '/api-gov/govexamgrade/areaList',
      })
        .then((response) => {
          if (!response.data.hasError) {
            const results = response.data.result
            this.areas = results
          } else {
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    // 填分分值列表
    getFillScoreList({ date = '', areaId = '' } = {}) {
      this.loading = true
      return this.axios({
        method: 'post',
        url: '/api-gov/govexamgradedetails/findItems',
        data: {
          date,
          areaId,
        },
      })
        .then((response) => {
          this.loading = false
          if (!response.data.hasError) {
            this.isShow = false
            const results = response.data.result
            this.formData.tableList = results
            if (this.formData.tableList.length < 1) {
              this.isShow = true
            }
          } else {
            this.isShow = true
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          this.loading = false
          this.isShow = true
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    // 保存分值配置
    saveScore(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let dataList = []
          for (let i = 0; i < this.formData.tableList.length; i++) {
            let scoreObj = {}
            let keyList = Object.keys(this.formData.tableList[i])
            keyList.forEach((v) => {
              if (v === 'detailScore' || v === 'id' || v === 'description') {
                Object.assign(scoreObj, { [v]: this.formData.tableList[i][v] })
              }
            })
            dataList.push(scoreObj)
          }
          let data = {
            areaId: this.filterField.areaId,
            date: this.filterField.date,
            detailData: JSON.stringify(dataList),
          }
          return this.axios({
            method: 'post',
            url: '/api-gov/govexamgradedetails/modifyItems',
            data,
          })
            .then((response) => {
              if (!response.data.hasError) {
                this.$message.success('保存成功')
              } else {
                this.$message.error(response.data.errorMsg)
              }
            })
            .catch((error) => {
              if (error.response) {
                this.$message.error(error.response.data)
              }
            })
        } else {
          this.$message.error('请按照提示规则输入内容!')
          return false
        }
      })
    },
    // 合并行
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        const _row = this.mergeSpan(this.formData.tableList).spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col,
        }
      }
    },
    // 合并行判断条件
    mergeSpan(tableData) {
      let spanArr = []
      let concat = 0
      tableData.forEach((item, index) => {
        if (index === 0) {
          spanArr.push(1)
        } else {
          if (item.classification === tableData[index - 1].classification) {
            //需合并相同内容的判断条件
            spanArr[concat]++
            spanArr.push(0)
          } else {
            spanArr.push(1)
            concat = index
          }
        }
      })
      return {
        spanArr,
      }
    },
    goBack() {
      this.$router.push({
        path: '/home/enterpriseScore/assessmentDetail',
        name: 'AssessmentDetail',
        query: {
          date: this.$route.query.date,
        },
      })
      this.$store.commit('GOBACK_NAME', {
        oldUrl: '/home/enterpriseScore/assessmentList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
  },
}
</script>

<style scoped lang="less">
.container {
  .mainCon {
    top: 196px;
    padding: 24px;
    .saveScore {
      margin: 40px auto;
    }
    /deep/ .el-table td {
      padding: 0;
    }
  }
}
</style>
